import eartest.ejb.SimpleEjb;
import org.apache.commons.lang3.StringUtils;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Nikita.Brazhnikov
 */
@WebServlet(urlPatterns = {"/numbers"}, displayName = "Numbers servlet")
public class NumbersServlet extends HttpServlet {

	@EJB()
	SimpleEjb numberEjb;

//	SimpleEjb numberEjb = new SimpleEjb();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String numberRequest = req.getParameter("number");
		if (StringUtils.isNotEmpty(numberRequest)) {
			log("Number request is " + numberRequest);
			try {
				String translation = numberEjb.getPronoun(numberRequest);
				req.setAttribute("translation", translation);
				goToPage(req, resp);
			} catch ( Exception e) {
				log("Exception while calling of the bean", e);
				req.setAttribute("error", e.getMessage());
				goToPage(req,resp);
			}
		} else {
			log("Number request is empty or null");
			req.setAttribute("error", "Request is empty");
			goToPage(req, resp);
		}
	}

	private void goToPage(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		req.getRequestDispatcher("numbers.jsp").forward(req, resp);
	}
}
